package com.coffee.tenant;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;

import java.util.HashSet;
import java.util.Set;

/**
 * 多租户
 * @author Songkui
 * @since 2024-04-16
 */
public class CoffeeTenantLineHandler implements TenantLineHandler {
    private final Set<String> ignoreTables = new HashSet<>();
    private final String column;
    private final boolean enabled;

    public CoffeeTenantLineHandler(CoffeeTenantConfigProperties properties){
        this.column = properties.getColumn();
        this.enabled = properties.isEnabled();
        properties.getIgnoreTables().forEach(table -> {
            ignoreTables.add(table.toLowerCase());
            ignoreTables.add(table.toUpperCase());
        });
    }
    @Override
    public Expression getTenantId() {
        return enabled ? new LongValue(TenantContextHolder.getTenantId()) : new LongValue(0L);
    }

    @Override
    public String getTenantIdColumn() {
        return this.column;
    }


    @Override
    public boolean ignoreTable(String tableName) {
        if (!enabled){
            return true;
        }

        Long tenantId = TenantContextHolder.getTenantId();
        if (tenantId == 0) {
            return true;
        }

        return TenantContextHolder.isIgnore() || CollUtil.contains(ignoreTables, tableName);
    }

}
